package com.tbit.main.controller;

import com.tbit.main.common.JsonResult;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.main.constant.OperateLog;
import com.tbit.main.controller.interceptor.LoginUserContextHolder;
import com.tbit.main.pojo.MoveConfig;
import com.tbit.main.service.MoveConfigService;
import com.tbit.main.util.Assert;
import com.tbit.main.util.DateTimeUtil;
import com.tbit.main.util.LogUtil;
import com.tbit.main.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 挪车配置
 *
 * @author Leon
 * 2020年4月8日 下午7:55:46
 */
@RestController
@RequestMapping("/moveConfig")
public class MoveConfigController {

    @Autowired
    private MoveConfigService moveConfigService;

    /**
     * 添加
     */
    @RequestMapping("/addOrUpdate")
    @OperateLog(module = ModuleEnum.MOVECONFIG, methods = MethodEnum.MOVECONFIG_ADD)
    public JsonResult add(MoveConfig moveConfig) {
        Assert.notNull(moveConfig.getAccountId(), "AccountUser.agentId.notNull");

        MoveConfig moveConfigDB = moveConfigService.getByAccountId(moveConfig.getAccountId());
        if (moveConfigDB == null) {
            if (moveConfig.getMoveDistance() == null) {
                moveConfig.setMoveDistance(0);
            }
            if (moveConfig.getSameParkPoint() == null) {
                moveConfig.setSameParkPoint(1);
            }
            if (moveConfig.getClearLastBorrowTime() == null) {
                moveConfig.setClearLastBorrowTime(1);
            }

            moveConfig.setUpdateTime(DateTimeUtil.getNowTime());

            moveConfigService.insert(moveConfig);
        } else {
            moveConfig.setUpdateTime(DateTimeUtil.getNowTime());

            /**替换可修改字段*/
            ObjectUtil.assign(moveConfig, moveConfigDB, null);

            moveConfigService.update(moveConfigDB);
        }

        LogUtil.info("修改挪车配置,人员：" + LoginUserContextHolder.getLoginUserId() + ",配置：" + moveConfig);
        return JsonResult.succ();
    }

    /**
     * 根据平台账号id查询
     */
    @RequestMapping("/getByAccountId")
    public JsonResult getByAccountId(Integer accountId) {
        Assert.notNull(accountId, "AccountUser.agentId.notNull");

        MoveConfig moveConfig = moveConfigService.getByAccountId(accountId);

        if (moveConfig == null) {
            moveConfig = new MoveConfig(accountId, 0, 0, 1, DateTimeUtil.getNowTime());
            moveConfigService.update(moveConfig);
        }

        return JsonResult.succ(moveConfig);
    }

}